﻿#include "AVPlayer.h"
#include "AVDumer.h"
#include "AVCommon.h"
#include <QDebug>
AVPlayer::AVPlayer()
    :AVdumer_(nullptr)
{
    avContext_ = new AVContext();   //装备AV上下文   每播放一个视频要封装
    AVdumer_.reset(new AVDumer(avContext_));    //创建解封装对象
}

AVPlayer::~AVPlayer()
{
    Close();
    if(AVdumer_)
    {
        AVdumer_.reset();
        AVdumer_ = nullptr;
    }
}

bool AVPlayer::Open(const QString &path)
{
    if(!path.isEmpty())
    {
        //开始解封装
        if(AVdumer_->Open(path.toStdString()) != 0)
        {
            return false;
        }
        playStatus_ = true;
        //启动视频渲染线程
        videoThread_.reset(new std::thread([this](){
            this->videoPlay();
        }));
        //启动音频渲染线程
        audioThread_.reset(new std::thread([this](){
            this->audioPlay();
        }));
        videoThread_->detach();
        audioThread_->detach();
        return true;
    }
    return false;
}


bool AVPlayer::Puase(const bool pause)
{
    if(!playStatus_)
    {
        return false;
    }
    return true;
}

bool AVPlayer::Volum(const qreal &v)
{
    if(!playStatus_)
    {
        return false;
    }
    return true;
}
//音频线程
void AVPlayer::audioPlay()
{
    AVFramePtr frame = nullptr;
    while (!quit_ && AVdumer_ && avContext_)
    {
        if (avContext_->audio_queue_.empty() || puase_)
        {
            std::this_thread::sleep_for(std::chrono::milliseconds(1));
            continue;
        }
        avContext_->audio_queue_.pop(frame);
    }
}
//视频线程
void AVPlayer::videoPlay()
{
    AVFramePtr frame = nullptr;
    while (!quit_ && AVdumer_ && avContext_ && videoFrameCb_)
    {
        std::this_thread::sleep_for(std::chrono::milliseconds(25));
        if (avContext_->video_queue_.empty() || puase_)
        {
            std::this_thread::sleep_for(std::chrono::milliseconds(1));
            continue;
        }
        //读视频帧队列
        avContext_->video_queue_.pop(frame);
        //播放视频帧

        //宽1080 高600 fmt bgra

        //开始渲染
        qDebug()<<"get one video frame";

    }
}

void AVPlayer::Close()
{
    playStatus_ = false;
    quit_ = true;
    puase_ = false;
}
